#include "include/DemoDAO.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <limits>

#ifdef _WIN32
#include <windows.h>
#endif

// 跨平台的环境变量获取
std::string getEnvVar(const std::string& varName, const std::string& defaultValue = "") {
    const char* value = std::getenv(varName.c_str());
    if (value && value[0] != '\0') {
        return std::string(value);
    }
    return defaultValue;
}

// 跨平台的控制台暂停
void pauseConsole() {
    std::cout << "Press Enter to continue...";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.get();
}

int main() {
    // 设置控制台编码 (Windows)
#ifdef _WIN32
    SetConsoleOutputCP(CP_UTF8);
    SetConsoleCP(CP_UTF8);
#endif

    std::cout << "Starting Demo Application..." << std::endl;
    std::cout << "Platform: " 
#ifdef _WIN32
              << "Windows"
#else
              << "Linux/Unix"
#endif
              << std::endl;

    // 从环境变量获取连接字符串
    std::string conn_string = getEnvVar("DEMO_DB_CONN", 
        "dbname=postgres user=postgres.your-tenant-id password=nodesbit host=192.168.0.210 port=5432");
    
    std::cout << "Using connection: " << conn_string.substr(0, conn_string.find("password=")) 
              << "password=***" << std::endl;
    
    try {
        DemoDAO dao(conn_string);
        
        if (!dao.isConnected()) {
            std::cerr << "Failed to connect to database: " << dao.getLastError() << std::endl;
            pauseConsole();
            return 1;
        }
        
        // 创建表
        if (!dao.createTable()) {
            std::cerr << "Failed to create table: " << dao.getLastError() << std::endl;
            pauseConsole();
            return 1;
        }
        
        // 演示操作
        int id1 = dao.insertData("Hello from " 
#ifdef _WIN32
            "Windows"
#else
            "Linux"
#endif
        );
        
        int id2 = dao.insertData("Cross-platform demo");
        
        // 批量插入
        std::vector<std::string> batchData = {
            "Batch data 1", 
            "Batch data 2", 
            "Batch data 3"
        };
        dao.batchInsert(batchData);
        
        // 查询所有数据
        dao.selectAll();
        
        // 最终查询
        std::cout << "\n=== Final State ===" << std::endl;
        dao.selectAll();
        
    } catch (const std::exception& e) {
        std::cerr << "Unexpected error: " << e.what() << std::endl;
        pauseConsole();
        return 1;
    }
    
    std::cout << "Application finished successfully!" << std::endl;
    pauseConsole();
    return 0;
}